TS 中的 never
•
# TS 中的 never
never 在 TS 中表示的是永远不会出现或者不存在的值。
一个简单的例子, 一个永远不会有返回值的函数:
```ts
function foo(): never {
throw new Error('error')
}
function infiniteLoop(): never {
while (true) {
}
}
```
有什么实际的使用场景呢?
比如我们可以用 never 排除一些我们不想要的值。
```ts
type NonNullable<T> = T extends null | undefined ? never : T
type FOO = NonNullable<number | null> // number
```
或者用于避免 switch case 或 if else 中会遗漏一些条件
```ts
type Foo = 'a' | 'b'
function fn(x: Foo) {
switch(x){
case 'a':
// ...
case 'b':
// ...
}
// 如果有一天将 Foo 的类型改为了 type Foo = 'a' | 'b' | 'c'
// 上面的代码并不会报错,但却遗漏了对 'c' 的处理
// 改为下方代码
type Foo = 'a' | 'b'
function fn(x: Foo) {
switch(x){
case 'a':
// ...
case 'b':
// ...
default:
// 如果我们将 Foo 改为 'a' | 'b' | 'c'
// 这里就会有 Type 'string' is not assignable to type 'never' 的报错
// 从而避免遗漏条件
const _exhaustiveCheck: never = x;
return _exhaustiveCheck;
}
```
https://www.typescriptlang.org/docs/handbook/2/functions.html#never
https://stackoverflow.com/questions/42291811/use-of-never-keyword-in-typescript
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-never-type